package com.example.springboot_sdse_air.service.impl;

import com.example.springboot_sdse_air.entity.User;
import com.example.springboot_sdse_air.mapper.UserMapper;
import com.example.springboot_sdse_air.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    public boolean register(String username, String password) {
        // 检查用户名是否已存在
        if (isUsernameExists(username)) {
            return false;
        }
        
        // 创建新用户
        User user = new User();
        user.setUsername(username);
        // 对密码进行MD5加密
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        
        // 插入数据库
        return userMapper.insert(user) > 0;
    }
    
    @Override
    public User login(String username, String password) {
        // 根据用户名查询用户
        User user = userMapper.selectByUsername(username);
        if (user == null) {
            return null;
        }
        
        // 验证密码
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if (user.getPassword().equals(encryptedPassword)) {
            return user;
        }
        
        return null;
    }
    
    @Override
    public boolean isUsernameExists(String username) {
        return userMapper.countByUsername(username) > 0;
    }
} 